package drds.server.handler;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import drds.server.datasource.IConnectionHolder;

public class GetConnectionHandler extends HandlerAdapter {
	private final CopyOnWriteArrayList<IConnectionHolder> connectionHolderList;
	private static final Logger LOGGER = LoggerFactory.getLogger(GetConnectionHandler.class);
	private final AtomicInteger finishedCount = new AtomicInteger(0);
	private final int totalNumber;

	public GetConnectionHandler(CopyOnWriteArrayList<IConnectionHolder> connectionHolderList, int totalNumber) {
		super();
		this.connectionHolderList = connectionHolderList;
		this.totalNumber = totalNumber;
	}

	public String getStatusInfo() {
		return "finished " + finishedCount.get() + " success " + connectionHolderList.size() + " target count:" + this.totalNumber;
	}

	public boolean finished() {
		return finishedCount.get() >= totalNumber;
	}

	@Override
	public void connectionAcquired(IConnectionHolder connectionHolder) {
		connectionHolderList.add(connectionHolder);
		finishedCount.addAndGet(1);
		LOGGER.info("connected successfuly " + connectionHolder);
		connectionHolder.release();
	}

	@Override
	public void connectionError(IConnectionHolder connectionHolder, Throwable e) {
		finishedCount.addAndGet(1);
		LOGGER.error("connect error " + connectionHolder + e);
		connectionHolder.release();
	}

	@Override
	public void errorResponse(IConnectionHolder connectionHolder, byte[] errorBytes) {
		LOGGER.error("caught error resp: " + connectionHolder + " " + new String(errorBytes));
		connectionHolder.release();
	}

}